package com.edu.util.process;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Yz
 * @ClassName: ProcessUtil
 * @Description: 命令执行解析
 * @date 2021/5/15
 */
public class ProcessUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProcessUtil.class);

    public static String parseResult(int result, Process process, String exec) throws IOException {
        StringBuffer desc = new StringBuffer();
        String temp = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        while (null != (temp = bufferedReader.readLine())) {
            desc.append(temp + "\n");
        }
        bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while (null != (temp = bufferedReader.readLine())) {
            desc.append(temp + "\n");
        }
        bufferedReader.close();
        LOGGER.info("{} result: {}, output: {}", exec, result, desc);
        if (process.isAlive()) {
            process.destroy();
        }
        return desc.toString();
    }

    public static void exec(String command, String dir) throws Exception {
        Process process = Runtime.getRuntime().exec(command, null, dir == null ? null : new File(dir));
        int code = process.waitFor();
        if (code != 0) {
            String result = parseResult(code, process, command);
            if (result != null) {
                throw new RuntimeException(command + ": " + result);
            }
        }
    }
}
